<template>
	<view class="wash-container">
		<!-- 顶部导航栏 -->
		<view class="top">
			<view>
				<image class="back" src="/static/images/白色左箭头.png" mode="" @click="goBack"></image>
			</view>
			<view class="title">专业洗车</view>

			<!-- 搜索框 -->
			<view class="search-section">
				<view class="search-box">
					<input type="text" placeholder="输入需要搜索的内容" placeholder-class="placeholder-style"
						v-model="searchText" @input="handleSearch">
				</view>
			</view>

			<!-- 历史记录标签 -->
		<!-- 	<view class="history-section">
				<view class="tag-list">
					<view v-for="(tag, index) in historyTags" :key="index" class="tag-item">
						{{ tag }}
					</view>
				</view>
			</view> -->
		</view>
		<!-- 洗车店列表 -->
		<scroll-view class="store-list" scroll-y>
			<view v-for="(store, index) in storeList" :key="index" class="store-item" @click="viewStoreDetail(store)">
				<view class="store-info">
					<view class="store-header">
						<text class="store-name">{{ store.name }}</text>
						<text class="store-distance">{{ store.distance }}</text>
					</view>
					
					<view class="stars">
						<text v-for="n in 5" :key="n" class="star" :class="{ 'active': n <= store.rating }">★</text>
						<text class="rating-text">{{ store.rating }}分</text>
					</view>

					<image :src="store.image" mode="aspectFill" class="store-image"></image>

					<view class="business-info">
						<text class="business-hours">营业时间：{{ store.startTime }}--{{ store.endTime }}</text>
						<text class="address">{{ store.address }}</text>
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue'

const searchText = ref('')
// const historyTags = ref(['飞飞洗车美容店'])
const storeList = ref([])
const userLocation = ref({
	latitude: null,
	longitude: null
})

// 获取用户当前位置
const getUserLocation = () => {
	return new Promise((resolve, reject) => {
		uni.getLocation({
			type: 'gcj02',
			success: (res) => {
				userLocation.value = {
					latitude: res.latitude,
					longitude: res.longitude
				}
				resolve(res)
			},
			fail: (error) => {
				console.error('获取位置失败:', error)
				uni.showToast({
					title: '获取位置失败，请检查定位权限',
					icon: 'none'
				})
				reject(error)
			}
		})
	})
}

// 计算两点之间的距离（使用Haversine公式）
const calculateDistance = (lat1, lon1, lat2, lon2) => {
	if (!lat1 || !lon1 || !lat2 || !lon2) return Infinity // 使用Infinity确保未知距离的店铺排在最后
	
	const R = 6371 // 地球半径，单位km
	const dLat = (lat2 - lat1) * Math.PI / 180
	const dLon = (lon2 - lon1) * Math.PI / 180
	const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
			  Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * 
			  Math.sin(dLon/2) * Math.sin(dLon/2)
	const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))
	const distance = R * c

	return distance // 返回实际距离（单位：km）
}

// 格式化距离显示
const formatDistance = (distance) => {
	if (distance === Infinity) return '未知'
	if (distance < 1) {
		return Math.round(distance * 1000) + 'm'
	} else {
		return distance.toFixed(1) + 'km'
	}
}

// 按距离排序店铺列表
const sortStoresByDistance = (stores) => {
	return stores.sort((a, b) => {
		const distanceA = calculateDistance(
			userLocation.value.latitude,
			userLocation.value.longitude,
			parseFloat(a.latitude),
			parseFloat(a.longitude)
		)
		const distanceB = calculateDistance(
			userLocation.value.latitude,
			userLocation.value.longitude,
			parseFloat(b.latitude),
			parseFloat(b.longitude)
		)
		return distanceA - distanceB
	}).map(store => ({
		...store,
		distance: formatDistance(calculateDistance(
			userLocation.value.latitude,
			userLocation.value.longitude,
			parseFloat(store.latitude),
			parseFloat(store.longitude)
		)),
		rating: store.rating || 4
	}))
}

// 获取洗车店列表
const fetchStoreList = () => {
	uni.request({
		url: 'http://localhost:9401/merchant/listByServiceType/3',
		method: 'GET',
		header: {
			'Authorization': uni.getStorageSync('Token')
		},
		success: (res) => {
			console.log('洗车店列表:', res)
			if (res.data.code === 200 && res.data.rows) {
				storeList.value = sortStoresByDistance(res.data.rows)
			} else {
				uni.showToast({
					title: res.data.msg || '获取洗车店列表失败',
					icon: 'none'
				})
			}
		},
		fail: (error) => {
			console.error('获取洗车店列表网络请求失败:', error)
			uni.showToast({
				title: '网络请求失败，请重试',
				icon: 'none'
			})
		}
	})
}

// 搜索洗车店
const handleSearch = () => {
	if (!searchText.value.trim()) {
		fetchStoreList()
		return
	}
	
	uni.request({
		url: 'http://localhost:9401/merchant/search',
		method: 'GET',
		data: {
			name: searchText.value
		},
		header: {
			'Authorization': uni.getStorageSync('Token')
		},
		success: (res) => {
			console.log('搜索结果:', res)
			if (res.data.code === 200 && res.data.rows) {
				storeList.value = sortStoresByDistance(res.data.rows)
			} else {
				uni.showToast({
					title: res.data.msg || '搜索失败',
					icon: 'none'
				})
			}
		},
		fail: (error) => {
			console.error('搜索洗车店网络请求失败:', error)
			uni.showToast({
				title: '网络请求失败，请重试',
				icon: 'none'
			})
		}
	})
}

const goBack = () => {
	uni.navigateBack()
}

const viewStoreDetail = (store) => {
	uni.navigateTo({
		url: `/pages/index/xiche/xichedetail/xichedetail?id=${store.id}`
	})
}

// 页面加载时获取用户位置和洗车店列表
onMounted(async () => {
	try {
		await getUserLocation()
		fetchStoreList()
	} catch (error) {
		console.error('初始化失败:', error)
	}
})
</script>

<style scoped>
	/* 背景图片 */
	.top {
		width: 100%;
		padding-bottom: 10px;
		background: url('../../../static/images/组 8.png');
		background-repeat: no-repeat;
		background-size: cover;
	}

	.top .back {
		position: absolute;
		left: 30rpx;
		top: 66rpx;
		width: 15px;
		height: 15px;
		z-index: 2;
	}

	.top .title {
		text-align: center;
		font-size: 18px;
		color: #fff;
		line-height: 44px;
		/* 根据实际需要调整 */
		padding-top: 20px;
	}

	.right-icons {
		width: 60rpx;
	}

	.icon {
		width: 48rpx;
		height: 48rpx;
	}

	.search-section {
		padding: 20rpx 30rpx;
	}

	.search-box {
		background: #FFFFFF;
		border-radius: 40rpx;
		height: 80rpx;
		display: flex;
		align-items: center;
		padding: 0 30rpx;
		position: relative;
	}

	.search-box input {
		flex: 1;
		height: 100%;
		font-size: 28rpx;
	}

	.placeholder-style {
		color: #999;
	}

	.search-icon {
		width: 40rpx;
		height: 40rpx;
		position: absolute;
		right: 30rpx;
	}

	.history-section {
		padding: 0 20rpx 20rpx;
	}

	.tag-list {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
		padding: 10rpx;
	}

	.tag-item {
		padding: 10rpx 30rpx;
		background: rgba(255, 255, 255, 0.2);
		border-radius: 30rpx;
		color: #FFFFFF;
		font-size: 24rpx;
	}

	.store-list {
		padding: 20rpx 0;
	}

	.store-item {
		background: #FFFFFF;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
	}

	.store-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 10rpx;
	}

	.store-name {
		font-size: 32rpx;
		font-weight: 500;
		color: #333;
	}

	.store-distance {
		font-size: 28rpx;
		color: #4080FF;
	}

	.stars {
		display: flex;
		align-items: center;
	}

	.star {
		color: #DDDDDD;
		font-size: 24rpx;
	}

	.star.active {
		color: #FFB800;
	}

	.rating-text {
		margin-left: 10rpx;
		font-size: 24rpx;
		color: #333;
	}

	.review-count {
		font-size: 24rpx;
		color: #999;
	}

	.store-image {
		width: 100%;
		height: 300rpx;
		border-radius: 10rpx;
		margin-bottom: 20rpx;
	}

	.business-info {
		font-size: 24rpx;
		color: #666;
	}

	.business-hours {
		margin-bottom: 10rpx;
		display: block;
	}

	.address {
		display: block;
	}
</style>